/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package com.plian.system.controller.pf;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.plian.Tools.*;
import com.plian.Tools.base.BaseController;
import com.plian.Tools.pagedata.PageData;
import com.plian.system.annotation.LogOperation;
import com.plian.system.common.status.CustomCode;
import com.plian.system.config.Resubmit;
import com.plian.system.entity.pf.BaseSalaryDetail;
import com.plian.system.model.CommonCode;
import com.plian.system.model.ListResult;
import com.plian.system.model.ObjResult;
import com.plian.system.model.R;
import com.plian.system.mybatis.search.SearchEntity;
import com.plian.system.mybatis.search.SearchParamEntiy;
import com.plian.system.mybatis.search.TokenSearch;
import com.plian.system.mybatis.support.Condition;
import com.plian.system.mybatis.support.Query;
import com.plian.system.service.pf.IBaseSalaryDetailService;
import com.plian.system.service.wf.FormWorkflowService;
import com.plian.system.vo.pf.BaseSalaryDetailVO;
import com.plian.system.wrapper.pf.BaseSalaryDetailWrapper;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;

/**
 * 市属企业工资总额本部职工明细表 控制器
 *
 * @author
 * @since 2019-09-27
 */
@RestController
@AllArgsConstructor
@RequestMapping("api/basesalarydetail")
public class BaseSalaryDetailController extends BaseController {

	private IBaseSalaryDetailService baseSalaryDetailService;

	private FormWorkflowService formWorkflowService;

	private BaseSalaryDetailWrapper baseSalaryDetailWrapper;

	/**
	 * 详情
	 */
	@PostMapping("/detail")
	public R<BaseSalaryDetailVO> detail(@RequestBody BaseSalaryDetail baseSalaryDetail) {
		BaseSalaryDetail detail = baseSalaryDetailService.getOne(Condition.getQueryWrapper(baseSalaryDetail));
		BaseSalaryDetailVO salaryDetailVO = baseSalaryDetailWrapper.entityToVO(detail);
		return baseSalaryDetailService.getDetailObj(salaryDetailVO);
	}

	/**
	 * 分页
	 */
	@PostMapping("/list")
	public ListResult<BaseSalaryDetailVO> list(@RequestBody Query query) {
		List<SearchEntity> entityList = query.getSearch();
		if (query.getAscs()==null&&query.getDescs()==null){
			query.setDescs("filling_year");
		}
		QueryWrapper<BaseSalaryDetail> queryWrapper = SearchParamEntiy.getQueryWrapper(
				Condition.getQueryWrapper(new BaseSalaryDetail()), entityList
		);
		TokenSearch<BaseSalaryDetail> tokenSearch = new TokenSearch<>();
		tokenSearch.addTokenQuery(queryWrapper, query);

		IPage<BaseSalaryDetail> pages = baseSalaryDetailService.page(Condition.getPage(query), queryWrapper);
		List<BaseSalaryDetailVO> salaryDetailVOS = baseSalaryDetailWrapper.entityToVO(pages.getRecords());
		ListResult<BaseSalaryDetailVO> listResult = new ListResult<>(CommonCode.SUCCESS);
		listResult.setList(salaryDetailVOS);
		listResult.setTotal(Long.valueOf(pages.getTotal()).intValue());
		return listResult;
	}

	/**
	 * 新增或修改
	 */
	@PostMapping("/submit")
	@Resubmit(delaySeconds = 0)
	@LogOperation("市属企业工资总额本部职工明细-提交")
	public R submit(@Valid @RequestBody BaseSalaryDetail baseSalaryDetail) {
		String checkMessage = baseSalaryDetailService.checkYear(baseSalaryDetail);
		if (StringUtil.isNotBlank(checkMessage)){
			return R.fail(checkMessage);
		}

		if (CollectionUtil.isEmpty(baseSalaryDetail.getSalaryDetails())){
			return R.fail("未填写数据");
		}
		boolean result = baseSalaryDetailService.submit(baseSalaryDetail);
		HashMap<String, Object> processVariable = new HashMap<>();
		formWorkflowService.startProcessAndSimulate(String.valueOf(baseSalaryDetail.getId()), baseSalaryDetail.getFormType(),processVariable);

		return R.status(result);
	}

	/**
	 * 删除
	 */
	@PostMapping("/remove")
	@LogOperation("市属企业工资总额本部职工明细-删除")
	public R remove(@RequestBody PageData pd) {
		List<String> ids = (List<String>)pd.get("ids");
		return R.status(baseSalaryDetailService.deleteLogic(Func.toLongList(StringUtils.join(ids, StringPool.COMMA))));
	}

	/**
	 * 市属企业工资总额本部职工明细表 根据填报时间 新增
	 * @param baseSalaryDetail
	 * @return
	 */
	@PostMapping("/initAdd")
	@Resubmit(delaySeconds = 0)
	@LogOperation("市属企业工资总额本部职工明细-根据填报时间新增")
	public R add(@RequestBody BaseSalaryDetail baseSalaryDetail){
		return baseSalaryDetailService.initAdd(baseSalaryDetail);
	}

	/**
	 * 覆盖导入 根据项目名称覆盖或新增
	 */
	@PostMapping("/excelCoverImport")
	@LogOperation("市属企业工资总额本部职工明细-导入")
	public ObjResult excelCoverImport(@RequestParam("file") MultipartFile multipartFile) throws IOException {
		String progressId = TokenUtil.getTokenUserId() + "_"+System.currentTimeMillis();
		CacheUtil.put("progress","progress",progressId + "#half:hour",0);
		InputStream inputStream = multipartFile.getInputStream();
		ServletRequestAttributes att = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		RequestContextHolder.setRequestAttributes(att, true);
		String token = att.getRequest().getHeader("token");
		att.setAttribute("token", token, RequestAttributes.SCOPE_SESSION);
		baseSalaryDetailService.importExcel(progressId, inputStream);
		ObjResult objResult = new ObjResult(CommonCode.SUCCESS);
		PageData pd = new PageData();
		pd.put("progressId", progressId);
		objResult.setPageData(pd);
		return objResult;
	}

	/**
	 * 导入进度查看
	 */
	@GetMapping("/progress/{progressId}")
	public ObjResult progress(@PathVariable String progressId){
		Object data = CacheUtil.get("progress", "progress", progressId + "#half:hour");
		if(data != null && data instanceof String){
			if ("导入成功".equals(data)){
				ObjResult objResult = new ObjResult(CommonCode.SUCCESS);
				PageData pd = new PageData();
				pd.put("data", 200);
				objResult.setPageData(pd);
				return objResult;
			}
			return new ObjResult(CustomCode.builder().message((String)data).code(1000).success(false).build());
		}
		ObjResult objResult = new ObjResult(CommonCode.SUCCESS);
		PageData pd = new PageData();
		pd.put("data", data);
		objResult.setPageData(pd);
		return objResult;
	}

	@GetMapping("/exportTemplateExcel")
//	@PassToken
	public void exportTemplateExcel(HttpServletResponse response, OutputStream os){
		baseSalaryDetailService.exportTemplateExcel(response, os);
	}

}
